package com.ruitu.mall_98_1.mvp.presenter;

import android.net.Uri;
import android.os.Handler;

import com.beanu.arad.base.my_base.Config;
import com.beanu.arad.utils.ToastUtils;
import com.ruitu.mall_98_1.dao.api.APIRetrofit;
import com.ruitu.mall_98_1.mvp.contract.MainHomeContract;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;
import com.ruitu.router_module.bean.app.HomeData;
import com.ruitu.router_module.bean.app.RongToken;
import com.ruitu.router_module.bean.app.RongUser;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/11/02
 */
public class MainHomePresenterImpl extends MainHomeContract.Presenter {

    @Override
    public void reqAppHome(String cityName, String accountId) {
        mModel.reqAppHome(cityName, accountId)
                .subscribe(new SubscriberImpl<BaseResult<HomeData>>() {
                    @Override
                    public void onError(Throwable e) {
                        mView.hideProgress();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(BaseResult<HomeData> baseResult) {
                        mView.hideProgress();
                        if (baseResult.isSuccess()) {
                            mView.onReqComplete(true, 1, baseResult.getData());
                        } else {
                            ToastUtils.showShort(baseResult.getMsg());
                        }
                    }
                });
    }

    @Override
    public void connectRong(final String appKey, final String nonce, final String timeStamp, final String signiture
            , final String userId, final String userName, final String portraitUri) {
        mModel.reqRongToken(appKey, nonce, timeStamp, signiture, userId, userName, portraitUri)
                .subscribe(new SubscriberImpl<RongToken>() {
                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(RongToken rongToken) {
                        String token = rongToken.getToken();//融云token
                        RongIM.connect(token, new RongIMClient.ConnectCallback() {
                            //Token 错误。可以从下面两点检查 1.Token是否过期,如果过期您需要向AppServer重新请求一个新的Token
                            //2.token 对应的appKey 和工程里设置的appKey 是否一致
                            @Override
                            public void onTokenIncorrect() {
                                ToastUtils.showShort("融云token错误");
                            }

                            @Override//连接融云成功
                            public void onSuccess(String userid) {
                                RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {
                                    @Override
                                    public UserInfo getUserInfo(final String rongId) {
//                                        Logg.i("自己的id = " + userId + ",回调id = " + rongId);
                                        APIRetrofit.getDefault().reqUserInfo(rongId)
                                                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                                                .subscribe(new SubscriberImpl<BaseResult<RongUser>>() {
                                                    @Override
                                                    public void onError(Throwable e) {
                                                        e.printStackTrace();
                                                    }

                                                    @Override
                                                    public void onNext(BaseResult<RongUser> userResult) {
//                                                        RongIM.getInstance().setMessageAttachedUserInfo(true);//是否携带用户信息,true携带,false不携带.
                                                        RongUser u = userResult.getData();
                                                        UserInfo userInfo = new UserInfo(u.getAccountId(), u.getName()
                                                                , Uri.parse(Config.BASE_URL + u.getHead()));
                                                        RongIM.getInstance().refreshUserInfoCache(userInfo);//刷新需要的用户信息
                                                    }
                                                });
                                        return null;//
                                    }
                                }, true);

                                mView.onReqComplete(true, 2, null);
                            }

                            @Override//连接融云失败
                            public void onError(RongIMClient.ErrorCode errorCode) {
                                if (isFirst) {
                                    ToastUtils.showShort("连接融云失败");
                                }
                                isFirst = false;
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        connectRong(appKey, nonce, timeStamp, signiture, userId, userName, portraitUri);
                                    }
                                }, 6000);
                            }
                        });
                    }
                });
    }

    @Override
    public void reqUnReadNum(String accountId) {
        mModel.reqUnReadNum(accountId)
                .subscribe(new SubscriberImpl<BaseResult<Integer>>() {
                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(BaseResult<Integer> baseResult) {
                        if (baseResult.isSuccess()) {
                            mView.onReqComplete(true, 3, baseResult.getData());
                        } else {
                        }
                    }
                });
    }

    private boolean isFirst = true;
}